﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Drawing;
using Intorise.Common;

namespace Model
{
    public partial class Player
    {
        Timer tradeTimer = null;
        ManualResetEvent tradeEvent = new ManualResetEvent(true);
        

        //交易
        private void StartTradeTimer()
        {
            if (this.Master == null)
            {
                ConsoleBLL.WriteLineError("仓库号没有配置，无法开始自动交易程序.."); return;
            }
            if (tradeTimer == null)
            {
                tradeTimer = new Timer(TradeMethod, null, 1000 * 60 * 30, 1000 * 60 * 30);//30分钟进行一次交易
            }
        }

        private void TradeMethod(object o)
        {
            ConsoleBLL.WriteLineWaring("开始执行交易程序..");
            Items.Clear();
          
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x97, 0x0D }); //整理背包
            Thread.Sleep(3000);

            
            AutoFight = false;
            //while (this.Status != PlayerStatusEnum.游戏中)
            //{
            //    Thread.Sleep(1000);
            //}
            this.Status = PlayerStatusEnum.交易物品;

            #region 交易
            ConsoleBLL.WriteLineInfo(string.Format("前往仓库号所在地进行交易..."));
            Transmit(Master.CurrentMap);    //移动到仓库号所在地图
            Thread.Sleep(1000);
            
                Change(1);
            
            Thread.Sleep(1000);
            //发送交易邀请
            tradeEvent.Reset();
            InviteTrade(Master.ID);
            //等待对方同意(60秒超时)
            if (!tradeEvent.WaitOne(1000 * 20))
            {
                ConsoleBLL.WriteLineError(string.Format("等待{0}同意交易超时，交易取消！", Master.ID)); InviteTrade(Master.ID);//return;
                goto end;
            }
            //Thread.Sleep(2000);
            //放入物品并锁定
            //lock (Items)
            //{
                for (int i = 0; i < Items.Count && i < 6; i++)
                {
                    PutItem(Items[i], (short)(i + 1));
                    Thread.Sleep(200);
                }
            //}
            Thread.Sleep(200);
            //放入金币
            var datas = new byte[] { 0x00, 0x01, 0xDD, 0x5F };
            for (int i = 0; i < GoldID.Length; i++)
            {
                datas = Tools.Contact(datas, GoldID[i]);
            }
            datas = Tools.Contact(net.GetNetworkBytes(datas.Length), datas);
            engine.SendData(datas);

            Thread.Sleep(500);
            Items.Clear();
            
            LockTrade();//发送锁定
            ConsoleBLL.WriteLineError(string.Format("{0}放入物品并锁定，等待仓库号锁定！", this));
            //等待对方锁定交易(60秒超时)
            tradeEvent.Reset();
            if (!tradeEvent.WaitOne(1000 * 20))
            {
                ConsoleBLL.WriteLineError(string.Format("等待{0}锁定交易超时，交易取消！", Master.ID)); //return;
                
            }
            
            AffirmTrade();//发送确认
            Thread.Sleep(1000);
            #endregion
            end:
            ConsoleBLL.WriteLineInfo(string.Format("{0} 交易已完成", this));
        }

        /// <summary>
        /// 邀请编号为id的玩家交易
        /// </summary>
        /// <param name="id"></param>
        private void InviteTrade(long id)
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x59 }, net.GetNetworkBytes(id), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 同意交易邀请
        /// </summary>
        /// <param name="id"></param>
        private void AgreeTrade()
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x5A }, net.GetNetworkBytes(this.ID), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 摆放物品
        /// </summary>
        /// <param name="item">物品</param>
        /// <param name="index">位置</param>
        private void PutItem(Thing item, short index)
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x5D }, net.GetNetworkBytes(index), net.GetNetworkBytes(item.InstanceID), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 锁定交易
        /// </summary>
        private void LockTrade()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0xDD, 0x61, 0x01, 0x01 });
        }

        /// <summary>
        /// 确认交易
        /// </summary>
        private void AffirmTrade()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0xDD, 0x61, 0x02, 0x01 });
        }

        //#region 交易处理器



        ///// <summary>
        ///// 确认交易处理器
        ///// </summary>
        ///// <param name="x"></param>
        ///// <returns></returns>
        //private bool ProcessAffirmTrade(Message x)
        //{
        //    GameHelper.Run(x, r =>
        //    {
        //        var item = new AffirmTradeMsg(x.Data);
        //        if (this.ID == Player.Master.ID)//当前号是仓库号，收到挂机号确认交易
        //        {
        //            ConsoleBLL.WriteLine(string.Format("收到挂机号{0}已确认交易", item.InvitePlayerID));
        //            tradeEvent.Set();
        //        }
        //        else//当前号是挂机号，收到仓库号确认交易
        //        {
        //            ConsoleBLL.WriteLine(string.Format("收到仓库号{0}已确认交易，交易已完成", Player.Master));
        //        }
        //    });
        //    return true;
        //}
        //#endregion
    }
}
